#!/usr/bin/env bash

readonly JAR_HOME=$(pwd)
readonly JAR_NAME="super-data-api.jar"

PID=0

functions="/etc/functions.sh"
if test -f $functions ; then
  . $functions
else
  success()
  {
    echo " SUCCESS! $@"
  }
  failure()
  {
    echo " ERROR! $@"
  }
  warning()
  {
    echo "WARNING! $@"
  }
fi

function checkpid() {
   PID=$(ps -ef | grep $JAR_NAME | grep -v 'grep' | awk '{print int($2)}')
    if [[ -n "$PID" ]]
    then
      return 0
    else
      return 1
    fi
}

function start() {
   checkpid
   if [[ $? -eq 0 ]]
   then
      warning "[$JAR_NAME]: already started! (PID=$PID)"
   else
      echo -n "[$JAR_NAME]: Starting ..."
      JAVA_CMD="nohup java -jar -Xms2g -Xmx2g $JAR_HOME/$JAR_NAME >/dev/null 2>&1  &"
      sh -c "$JAVA_CMD"
      sleep 3
      checkpid
      if [[ $? -eq 0 ]]
      then
         success "(PID=$PID) "
      else
         failure " "
      fi
   fi
}

function stop() {
   checkpid
   if [[ $? -eq 0 ]];
   then
      echo -n "[$JAR_NAME]: Shutting down ...(PID=$PID) "
      kill  $PID
      sleep 5
      if [[ $? -eq 0 ]];
      then
         success " "
      else
         failure " "
      fi
   else
      warning "[$JAR_NAME]: is not running ..."
   fi
}

function status() {
   checkpid
   if [[ $? -eq 0 ]]
   then
      success "[$JAR_NAME]: is running! (PID=$PID)"
      return 0
   else
      failure "[$JAR_NAME]: is not running"
      return 1
   fi
}

case "$1" in
   'start')
      start
      ;;
   'stop')
     stop
     ;;
   'restart')
     stop
     start
     ;;
   'status')
     status
     ;;
    *)
     echo "Usage: $0 {help|start|stop|restart|status}"
     ;;
esac
exit 0

